<template>
    <div class="showQuestion" id="top">
        <div class="topTwoButton">          
            <el-badge :value="state.selectQuestionList.length" class="item">
                <el-tooltip content="查看选中题目" effect="dark">
                    <el-button :icon="ShoppingCart" size="large" circle @click="showManyQuestionReadOnlyClick()" /> 
                </el-tooltip> 
            </el-badge>
            
            <el-tooltip content="去组卷" effect="dark">
                <el-button :icon="Promotion" size="large" circle @click="GroupQuestionListClick()" /> 
            </el-tooltip>
        </div>
        <el-table ref="multipleTableRef" class="tableClass" :data="state.currentPageQuestionList" stripe
            max-height="600" 
            :row-style="{height:50+'px'}" 
            :cell-style="{padding:0+'px'}" 
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            border
        >
            <!-- <el-table-column type="selection" width="35" /> -->
            <el-table-column type="index" width="45" label="序" />
            <el-table-column width="700" property="content" label="内容" show-overflow-tooltip />
            <el-table-column width="100" property="knowledgepoint_cn" label="知识点" show-overflow-tooltip />
            <el-table-column align="right" width="85" >
                <template #header>
                    操作
                </template>
                <template #default="scope">
                  <!-- <el-tooltip v-if="scope.row.open-level=='private'"
                    class="box-item"
                    effect="dark"
                    content="设为公开"
                    placement="top"
                    >
                      <el-icon style="width: 1em; height: 1em; margin-right: 1px" @click="cancelFavoriteQuestionClick(scope.$index)">
                          <Unlock />
                      </el-icon>
                    </el-tooltip>
                    <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="设为私密"
                    placement="top"
                    >
                      <el-icon style="width: 1em; height: 1em; margin-right: 1px" @click="cancelFavoriteQuestionClick(scope.$index)">
                          <Lock />
                      </el-icon>
                    </el-tooltip> -->
                    <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="取消收藏"
                    placement="top"
                    >
                      <el-icon style="width: 2em; height: 2em; margin-right: 1px" @click="cancelFavoriteQuestionClick(scope.$index)">
                          <RemoveFilled />
                      </el-icon>
                    </el-tooltip>
                    <el-tooltip
                    class="box-item"
                    effect="light"
                    content="加入组卷"
                    placement="top"
                    >
                      <el-icon style="width: 2em; height: 2em; margin-left: 1px" @click="addToSelectQeustionList(scope.row)">
                          <CirclePlus />
                      </el-icon>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
      </div>
    <div class="pagination">
        <el-pagination
        background
        layout="total, pre, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
    </div>
 
    <ViewQuestionDetail ref="viewQuestionDetail" :question="state.question" />
    <!-- <EditeOneQuestionDialoge ref="editeOneQuestionDialoge" :type=state.type :question="state.question" :father_method="modifySelectedQuestionList" />    -->
    <ShowQuestionReadOnlyDialog ref="showManyQuestionReadOnlyDialog" :questionList="state.selectQuestionList" />

  </template>
  
  <script setup>
    import { reactive, ref, onMounted, onUnmounted, computed } from 'vue'
    import axios from '@/utils/axios'
    import { useRoute, useRouter } from 'vue-router'
    import ViewQuestionDetail from '@/views/ViewQuestionDetail.vue'
    import { View, ShoppingCart, Plus, Promotion, QuestionFilled, EditPen, CirclePlus, Star, StarFilled, Unlock, Lock} from '@element-plus/icons-vue'
    // import EditeOneQuestionDialoge from '@/views/EditeOneQuestionDialoge.vue'
    import ShowQuestionReadOnlyDialog from '@/views/ShowQuestionReadOnlyDialog.vue'
    import { ElMessage } from 'element-plus'
    import { useStore } from 'vuex'
    import { localGet } from '@/utils'
  
    const store=useStore()
    const showManyQuestionReadOnlyDialog = ref()
    const top = ref()
    const viewQuestionDetail = ref()
    const multipleTableRef = ref()
    const select_order_number = ref('') //表格select选中的条数
    const select_orderId = ref([]) //表格select复选框选中的id
    const multipleSelection = ref([])  
    const route = useRoute()
    const router = useRouter()  
    
    const state = reactive({   
      userFavoriteQuestionList: [], // 该用户收藏的题目
      currentPageQuestionList: [],  //当前页码显示的题目
      total: 0, // 总条数
      currentPage: 1, // 当前页
      pageSize: 10, // 分页大小
      selectQuestionList: [],   //选中的题目列表
 
    })
    //监听路由变化
    const unWatch = router.beforeEach((to, from, next) => { 
      const {id, page, size} = to.query
      state.id = id
      state.page = page
      state.size = size
      state.currentPage = 1     
      return next(true)
    })
    
    //初始化
    onMounted(()=>{    
      const {id} = route.query
      // state.knowledgepointId = id
      state.id = id
      state.currentPage = 1
      getAllFavoriteQuestionsByPage()
      scrollToTop()
    })
    onUnmounted(()=>{
      unWatch()
    })
    //根据当前路由名选择执行相应的函数，请求不同的后端apiName
   
    //点击页码时触发
    const handleCurrentChange = (newPage)=>{
      state.currentPage = newPage 
      getAllFavoriteQuestionsByPage()
      scrollToTop()      
    }
    //更改每页数量时触发
    const handleSizeChange = (newSize)=>{
      state.pageSize = newSize
      state.currentPage=1
      getAllFavoriteQuestionsByPage()
      scrollToTop()
    }
    const scrollToTop=()=>{
      document.querySelector('#top').scrollIntoView(true);
    }
    //把\n转换成<br>
    const convertEnter2br = (str)=>{
      return str.replace(/\\n/g, "<br>")
    }
    //把questionList中的题目内容、答案、详解\n转换成<br>
    const convertQuestionListEnter2br = (array)=>{
      for(let i=0;i<array.length;i++){
        array[i].content = convertEnter2br(array[i].content)
        array[i].answer = convertEnter2br(array[i].answer)
        array[i].explain = convertEnter2br(array[i].explain)
      }
      return array
    }
 
    //查看单个题目详情
    const viewDetail = (item)=>{
      item.content = convert2HTML(item.content)
      state.question = item
      if (state.question.pictures){
        state.question.images = state.question.pictures.split("-")
      }
      viewQuestionDetail.value.open(item)
    }   

    // 查看购物车已选题目列表
    const showManyQuestionReadOnlyClick = ()=>{
      // 打开弹窗
      if(state.selectQuestionList){
        showManyQuestionReadOnlyDialog.value.open(state.selectQuestionList)
      }else{
        ElMessage.success( '请勾选题目！')
      }    
    }
 
    // 选中的题目存入全局状态，addPaperBySelectQuestionList把选中的题目列表提交给后台，生成docx文件，后台返回该docx的url
    const GroupQuestionListClick = ()=>{      
      store.commit('setSelectQuestionList', state.selectQuestionList)
      console.log("从收藏传到全局啦",state.selectQuestionList)
      router.push("/addPaperBySelectQuestionList")
    } 
  
    // 获取该用户所有收藏的题目,按照分页
    const getAllFavoriteQuestionsByPage=()=>{
      let params = {page:state.currentPage, size:state.pageSize}
      axios.get(`/GetAllFavoriteQuestionsByPageAPIView/`,{params}).then(res => {
        if (res.code==200){
          console.log("获取收藏题目成功：", res)
          state.currentPageQuestionList = res.data.results
          state.total = res.total
          // convertQuestionListEnter2br(state.currentPageQuestionList)
        }else{
          ElMessage.error("获取收藏题目失败")
          console.log("获取题目失败：",res)
          if (res.code==403){
            ElMessage.error("重新登录")
            // router.push("/login")
          }
        }
      })
      .catch((error)=>{
        console.log("获取收藏题目错误", error)
      })   
    }
  // 取消收藏该题目
  const cancelFavoriteQuestionClick=(index)=>{
      axios.delete(`/UserFavoriteQuestionAPIView?question_id=${index}&page=${state.currentPage}&size=${state.pageSize}`).then(res => {
        if (res.code==200){
          ElMessage("取消收藏成功！")
          state.currentPageQuestionList = res.data.results          
        }else{
          ElMessage("取消收藏失败")
          if (res.code==403){
            ElMessage.error("重新登录")
            // router.push("/login")
          }
        }
      })
      .catch((error)=>{
        console.log("取消收藏错误", error)
      })   
    }
  const addToSelectQeustionList=(item)=>{
    state.selectQuestionList.push(item)
    ElMessage.success("加入组卷成功")
    console.log('加入组卷成功',state.selectQuestionList)
  }
  </script>

  <style scoped>
  html, body {
      width: 100%;
      height: 100%;
  }
  .showQuestion{
    display: flex;
    flex-direction: column;;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    margin: 1;
    padding: 1;
  }
    .item {
      margin-bottom: 1px;
    }
 

    
  .tableClass cell{   
      padding: 0!important;
      height: 600px!important;
      line-height: 20px!important;
      text-align: center;
      font-size: 10px;
    }
  
    .pagination{
      display: flex;
      flex-flow: row nowrap;
      justify-content: center;
      align-items: center;
    }
    .operateButton{
      padding: 0;
      margin: 0;
      display: flex;
      flex-flow: row nowrap;
    }
    .topTwoButton{
      display: flex;
      flex-flow: row nowrap;
      justify-content: space-between;
      align-items: center;
    }
  </style>